package com.jhws.business.comm.controller;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import com.jhws.common.base.bo.JsonRespData;
import com.jhws.common.*;
import com.jhws.common.base.bo.Global;
import net.sf.json.JSONArray;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jhws.business.comm.bo.TblAreaDimBo;
import com.jhws.business.comm.bo.TblBuildingDimBo;
import com.jhws.business.comm.bo.TblCommDimBo;
import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.business.comm.bo.TblAreaDimForm;
import com.jhws.business.comm.service.ITblAreaDimService;
import com.jhws.business.comm.service.ITblBuildingDimService;
import com.jhws.business.comm.service.ITblCommDimService;
import com.jhws.sys.menu.service.ITblMenuDimService;
import com.jhws.sys.appUser.service.ITblSipAcountDimService;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.util.commUtil;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/AreaCtrl")
public class AreaCtrl 
{
	@Resource
	protected ITblSipAcountDimService ITblSipAcountDimService;
	@Resource
	protected ITblUserDimService ITblUserDimService;
	@Resource
	protected ITblAreaDimService ITblAreaDimService;
	@Resource
	protected ITblCommDimService ITblCommDimService;
	@Resource
	protected ITblBuildingDimService ITblBuildingDimService;
	@Resource
	protected ITblMenuDimService ITblMenuDimService;

	@RequestMapping("query.x")
	public String queryTblAreaDim(TblAreaDimForm TblAreaForm,int page,
			javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws java.lang.Exception
	{
		int currPage = page > 0 ?page:1;
		
		TblUserDimBo userInfo = (TblUserDimBo) request.getSession().getAttribute(
				TblUserDimBo.USER_INFO_REFERENCE);
		
		if (userInfo.getUserState().equals("0")) {
			request.setAttribute("message", "用户已被禁用，请联系管理员");
			return "login";
		}
		
		String where="where 1=1 ";
		String strAreaName = MyRequest.GetString(request, "strAreaName");
		if(!strAreaName.equals("")){
			where = where +" and area_name like '%"+strAreaName+"%' ";
		}
		String whereClause = StringUtils.isNotEmpty(userInfo.getCommCode()) ? "where comm_code = '" + userInfo.getCommCode() + "'" : "";
		
		String strCommCode = MyRequest.GetString(request, "strCommCode");
		
		if(!strCommCode.equals("")){
			where = where + " and comm_code='"+strCommCode +"' ";
			request.setAttribute("commStr", "'" + strCommCode + "'");
		}
		else
		{
			if(null != userInfo && StringUtils.isNotEmpty(userInfo.getCommCode())){
				where = where + " and comm_code ='" + userInfo.getCommCode() +"' ";
				request.setAttribute("commStr", "'" + userInfo.getCommCode() + "'");
			}
		}
		request.setAttribute("strAreaName", strAreaName);
		request.setAttribute("strCommCode", strCommCode);
		
		List<TblCommDimBo> commlist = ITblCommDimService.findTblCommDimByWhere(whereClause);
		request.setAttribute("commlist", commlist);
		
		int pageSize = TblAreaForm.getPageSize();
		int beginIndex = pageSize * (currPage - 1);

		Page TblAreaDims = ITblAreaDimService.findTblAreaDim(beginIndex,
				pageSize, where);
		
		List<TblAreaDimBo> allList = ITblAreaDimService.findTblAreaDimByWhere(where);
		request.getSession().setAttribute("queryAreaList", allList);
		
		PageRoll pr = new PageRoll(request, pageSize, currPage,
				TblAreaDims.getTotalNumber());
		request.setAttribute("pr", pr.Show(true, true, true, true));
		request.setAttribute("tblAreaDims", TblAreaDims);

		return "business/areaDim/queryTblAreaDim";

	}

	@RequestMapping("forSave.x")
	public String forSaveTblAreaDim(TblAreaDimForm TblAreaForm,
			javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws java.lang.Exception {

		try {
			TblAreaDimBo bo = this.ITblAreaDimService.findTblAreaDimById(
					TblAreaForm.getAreaCode(), TblAreaForm.getCommCode());
			BeanUtils.copyProperties(TblAreaForm, bo);

			return "business/areaDim/addTblAreaDim";
		} catch (Exception e) {
			request.setAttribute("message", e.getMessage());
			request.setAttribute("backurl",
					"/AreaCtrl/query.x?page=1");
			return "share/commonerror";
		}
		
	}
	
	@RequestMapping("save.x")
	public String saveTblAreaDim(TblAreaDimForm TblAreaForm,
			javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws java.lang.Exception {

		TblAreaDimBo bo = new TblAreaDimBo();

		String strurl = ITblMenuDimService.getMenuString("/AreaCtrl/query.x");
		try {
			BeanUtils.copyProperties(bo, TblAreaForm);// 属性拷贝
			
			ITblAreaDimService.save(bo);
			SysLogger.logInfo(request, "修改栋数信息,栋数编号："+bo.getAreaCode());
			request.setAttribute("message", "修改栋数信息成功！");
			request.setAttribute("backurl",
					"/AreaCtrl/query.x?page=1&"+strurl);
			return "share/commonsuccess";
		} catch (Exception e) {
			request.setAttribute("message", e.getMessage());
			request.setAttribute("backurl",
					"/AreaCtrl/query.x?page=1&"+strurl);
			return "share/commonerror";
		}

	}

	@RequestMapping("addBatchs.x")
	@ResponseBody
	public JsonRespData addBatchs(String commCode,String commName,String [] areaParams)
			throws java.lang.Exception {

		for(String param : areaParams){
			String [] params = param.split("-");
			if(params.length < 5)
				continue;

			for(int i=1;i<=Integer.valueOf(params[1]);i++){
				TblBuildingDimBo bo = new TblBuildingDimBo();
				bo.setCommCode(commCode);
				bo.setAreaName(Integer.valueOf(params[0])+"");
				bo.setCommName(commName);
				bo.setBuildingName(i+"");
				bo.setSectionName(params[2]);
				bo.setDevNumber(Integer.valueOf(params[4]));
				bo.setAreaAliasName(params[3]);
				bo.setAreasInSection(params[5]);
				bo.setBuildingType(Integer.valueOf(params[6]));
				if(Integer.valueOf(params[6]) == Global.BUILDING_NORMAL) {
					bo.setBuildingAliasName(bo.getBuildingName() + "单元");
					bo.setBuildingType(Global.BUILDING_NORMAL);
				}
				else if(Integer.valueOf(params[6]) == Global.BUILDING_VILLA) {
                    bo.setBuildingAliasName(bo.getBuildingName() + "号别墅");
					bo.setBuildingType(Global.BUILDING_VILLA);
                }

				ITblBuildingDimService.save(bo);
			}
		}
		return new JsonRespData("",1,"");

	}

	@RequestMapping("genArea.x")
	public String genAreaDim(TblAreaDimForm TblAreaForm,
			javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws java.lang.Exception {

		String strurl = ITblMenuDimService.getMenuString("/AreaCtrl/query.x");
		String commCode = MyRequest.GetString(request, "commCode");
		if (StringUtils.isEmpty(commCode)) {
			request.setAttribute("message", "小区编号为空！");
			request.setAttribute("backurl",
					"/comm/query.x?page=1&"+strurl);
			return "share/commonerror";
		}
		
		commCode = commUtil.appendZero(commCode);
		
		TblCommDimBo bo = ITblCommDimService.findTblCommDimById(commCode);
		if (bo == null) {
			request.setAttribute("message", "小区编号[" + commCode + "]的小区不存在");
			request.setAttribute("backurl",
					"/comm/query.x?page=1&"+strurl);
			return "share/commonerror";
		}
		String commName = bo.getCommName();

		request.setAttribute("commName", commName);
		request.setAttribute("commCode", commCode);

		return "business/areaDim/genAreaDim";
	}
	
	@RequestMapping("findArea.x")
	public String findAreaDimList(
			javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws java.lang.Exception 
	{
		String commCode = MyRequest.GetString(request, "commCode");
		if (StringUtils.isEmpty(commCode))
		{
			return "null";
		}
		commCode = commUtil.appendZero(commCode);
		commCode = "where comm_code = '" + commCode + "' ";
		List<TblAreaDimBo> boList = ITblAreaDimService.findTblAreaDimByWhere(commCode);
		request.setAttribute("boList", boList);
		
		try {
			JSONArray array = JSONArray.fromObject(boList);
			JSONArray ja = JSONArray.fromObject(array);
			request.setAttribute("ja", ja);
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(ja.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "null";
	}
	
	@RequestMapping("checkAreaGen.x")
	@ResponseBody
	public JsonRespData checkAreaGen(String commCode, @RequestParam String []areaName) throws Exception
	{

		String where = "where comm_code = '"+commCode+"' and areaName in (";
		String areaStr = "";
		for(int i = 0; i < areaName.length; i++){
			areaStr += "'"+areaName[i]+"'";
			if(i!=areaName.length-1)
				areaStr+=",";
		}
		where += areaStr+")";

		List<TblBuildingDimBo> list = ITblBuildingDimService.findTblBuildingDimByWhere(where);
		if(list != null && list.size() != 0){
			String error = "以下楼栋已存在:";
			for(TblBuildingDimBo bo : list){
				error += bo.getAreaName()+" ";
			}
			return new JsonRespData("",-1,error);
		}
		return new JsonRespData("",1,"");
	}

	@RequestMapping("remove.x")
	public String removeTblAreaDim(
			javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws java.lang.Exception
	{
		//TblAreaDimForm TblAreaForm = (TblAreaDimForm) form;
		String strurl = ITblMenuDimService.getMenuString("/AreaCtrl/query.x?page=1");
		String objectList = request.getParameter("objectList");
		String AreaCode = request.getParameter("areaCode");
		String commCode = request.getParameter("commCode");
		String commStr = MyRequest.GetString(request, "commStr");
		String selectAll = request.getParameter("selectAll");
		
		if (null != selectAll && StringUtils.isNotEmpty(selectAll))
		{
			boolean isFail = false;
			
			@SuppressWarnings("unchecked")
			List<TblAreaDimBo> allList = (List<TblAreaDimBo>) request.getSession().getAttribute("queryAreaList");
			for (TblAreaDimBo bo : allList)
			{
				String where ="where 1=1 and comm_code='"+ bo.getCommCode() +"' and area_code='"+bo.getAreaCode() +"'";
				List<TblBuildingDimBo> list = ITblBuildingDimService.findTblBuildingDimByWhere(where);
				if(list != null && list.size() > 0)
				{
					isFail = true;
					continue;
				}
				else
				{
					this.ITblAreaDimService.removeDim(bo.getAreaCode(), bo.getCommCode());
				}
			}
			if (isFail)
			{
				request.setAttribute("message", "栋数信息下存在单元信息，请先删除单元信息！");
				request.setAttribute("backurl",
						"/buildingDim.do?method=queryTblBuildingDim"+strurl);
				return "share/commonerror";
			}
			//this.getTblUnitDimService().removeAllDim(allList);
			request.setAttribute("message", "批量删除栋数信息成功！");
		}
		else if (null != objectList && StringUtils.isNotEmpty(objectList))
		{
			String[] strs = objectList.split("_");
			boolean isFail = false;
			for (String s : strs)
			{
				String[] areaInfo = s.split(",");
				String where ="where 1=1 and comm_code='"+ areaInfo[0] +"' and area_code='"+ areaInfo[1] +"'";
				List<TblBuildingDimBo> list = ITblBuildingDimService.findTblBuildingDimByWhere(where);
				if(list!=null && list.size()>0)
				{
					isFail = true;
				}
				else
				{
					this.ITblAreaDimService.removeDim(areaInfo[1], areaInfo[0]);
				}
			}
			if (isFail)
			{
				request.setAttribute("message", "栋数信息下存在单元信息，请先删除单元信息！");
				request.setAttribute("backurl",
						"/areaDim.do?method=queryTblAreaDim"+strurl);
				 return "share/commonerror";
			}
			request.setAttribute("message", "批量删除栋数信息成功！");
		}
		else
		{
			String where ="where 1=1 and comm_code='"+ commCode +"' and area_code='"+AreaCode +"'";
			List<TblBuildingDimBo> list = ITblBuildingDimService.findTblBuildingDimByWhere(where);
			if(list!=null && list.size()>0){
				request.setAttribute("message", "栋数信息下存在单元信息，请先删除单元信息！");
				request.setAttribute("backurl",
						"/areaDim.do?method=queryTblAreaDim"+strurl);
				return  "share/commonerror";
			}
			this.ITblAreaDimService.removeDim(AreaCode, commCode);
			SysLogger.logInfo(request, "删除栋数信息,小区编号："+commCode+",栋数编号："+AreaCode);
			request.setAttribute("message", "删除栋数信息成功！");
		}
		
		request.setAttribute("backurl", "/areaDim.do?method=queryTblAreaDim"+strurl);
		return "share/commonsuccess";
	}


}
